/**
 * 
 */
package com.lorizz.picpub.task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author wind hong
 * 
 */
public class TaskEnqueueManager implements Runnable {

    private Log log = LogFactory.getLog(getClass());

    private BlockingQueue<Long> taskQueue;
    private TaskSelector taskSelector;

    public void setTaskSelector(TaskSelector taskSelector) {
        this.taskSelector = taskSelector;
    }

    public void setTaskQueue(BlockingQueue<Long> taskQueue) {
        this.taskQueue = taskQueue;
    }

    @Override
    public void run() {
        List<Long> taskIds = taskSelector.selectIds();
        List<Long> taskIdsTmp = new ArrayList<Long>();
        taskIdsTmp.addAll(taskIds);
        for (Long id : taskIds) {
            try {
                log.debug(String.format("Enqueueing task with id [%d]", id));
                taskQueue.put(id);
                taskIdsTmp.remove(id);
            } catch (InterruptedException e) {
                log.error(String.format("Enqueued task with id [%d] error. Rolling back the others.", id), e);
                try {
                    taskSelector.returnIds(taskIdsTmp);
                } catch (Exception e1) {
                    log.error("Returning IDs error: " + taskIdsTmp, e1);
                    throw new RuntimeException(e1);
                }
            }
        }
        
    }

}
